﻿using IOP.SgrA;
using IOP.SgrA.ECS;
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
using IOP.Extension.DependencyInjection;
using System.Linq;

namespace VkSample102
{
    public class BounceSystem : ComponentSystem
    {

        private float startY = 3;
        private float currentY = 3;
        private float vy = 0;
        private float g = 5.0f;
        private float timeLive = 0;

        public override void Initialization()
        {
        }

        public override void Update(TimeSpan timeSpan)
        {

            timeLive += (float)timeSpan.TotalSeconds;
            float tempCurrY = startY - 0.5f * g * timeLive * timeLive + vy * timeLive;
            if (tempCurrY <= 0)
            {
                startY = 0;
                vy = -(vy - g * timeLive) * 0.995f;
                timeLive = 0;
                if (vy < 0.35f)
                {
                    currentY = 0;
                }
            }
            else
            {
                currentY = tempCurrY;
            }

            ContextManager.Foreach<BallGroup>((group) =>
            {
                Context context = ContextManager.GetContext(group.Entity);
                var obj = context.GetContextRenderObject();
                context.SetCustomPropery("ifMimage", false);
                ref MVPMatrix mvp = ref context.GetMVPMatrix();
                mvp.ModelMatrix = Matrix4x4.CreateTranslation(0, currentY + 0.5f, 0);
                context.PushToRenderGroup();
                foreach (var child in obj.GetChildrens())
                {
                    var trans = child.GetComponents<Transform>().First();
                    trans.Position = new Vector3(0, currentY + 0.5f, 0);
                    trans.Scaling = new Vector3(1, -1, 1);
                }
            });
            ContextManager.Foreach<MirrorGroup>((group) =>
            {
                Context context = ContextManager.GetContext(group.Entity);
                var obj = context.GetContextRenderObject();
                var trans = obj.GetComponents<Transform>().First();
                context.SetCustomPropery("ifMimage", true);
                ref MVPMatrix mvp = ref context.GetMVPMatrix();
                mvp.ModelMatrix = Matrix4x4.CreateTranslation(0, currentY + 0.5f, 0) * 
                Matrix4x4.CreateScale(new Vector3(1, -1, 1));
                context.PushToRenderGroup();
            });
        }
    }
}
